package com.example.exercise;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: dangwen
 * @createDate: 2021/6/17
 * ReentrantLock 、 Condition
 */
public class ProducerAndConsumer02 {

    private final static int MAX = 20;
    private final static int MIN = 0;

    static Lock lock = new ReentrantLock();
    static Condition full = lock.newCondition();
    static Condition empty = lock.newCondition();

    static class Gun{
        private int num;

        void input(){
            lock.lock();
            try {
                while (num >= MAX){
                    System.out.println("子弹已满！");
                    full.await();
                }
                num++;
                System.out.println("填入子弹，现在的子弹数量为：" + num);
                empty.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
                System.out.println("释放锁");
            }

        }

        void output(){
            lock.lock();
            try {
                while (num <= MIN){
                    System.out.println("枪膛已空！");
                    empty.await();
                }
                num--;
                System.out.println("射出子弹，现在的子弹数量为：" + num);
                full.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }

        }
    }

    static class Producer implements Runnable{
        private Gun gun;
        public Producer(Gun gun){
            this.gun = gun;
        }

        @Override
        public void run() {
            while (true){
                gun.input();
            }
        }
    }

    public static class Consumer implements Runnable{

        private Gun gun;

        public Consumer(Gun gun){
            this.gun = gun;
        }

        @Override
        public void run() {
            while (true){
                gun.output();
            }
        }
    }

    public static void main(String[] args) {
        Gun gun = new Gun();
        new Thread(new Producer(gun)).start();
        new Thread(new Consumer(gun)).start();
    }
}
